package top.cluski.feieprint.utils;

import cn.hutool.crypto.SecureUtil;
import com.dtflys.forest.Forest;
import lombok.extern.slf4j.Slf4j;
import top.cluski.feieprint.config.FeiEConfig;
import top.cluski.feieprint.domain.dto.FeiEPrintErrorContext;
import top.cluski.feieprint.exception.FeiEPrintException;

@Slf4j
public class FeiEPrintUtils {
    public static FeiEConfig feiEConfig;

    public static void request(String name, String content) {
        FeiEConfig.Printer printer = feiEConfig.getPrinters().get(name);
        if (printer == null) {
            log.warn("暂未找到对应的打印机 name={}", name);
            throw new FeiEPrintException(new FeiEPrintErrorContext(FeiEPrintErrorContext.MainError.PARAM_ERROR,
                    FeiEPrintErrorContext.SubError.PRINTER_NOT_FOUND, name), "暂未找到对应的打印机");
        }
        try {

            String stime = String.valueOf(System.currentTimeMillis() / 1000);
            String res = Forest.post("https://api.feieyun.cn/Api/Open/")
                    .contentFormUrlEncoded()
                    .addBody("user", printer.getUser())
                    .addBody("stime", stime)
                    .addBody("apiname", "Open_printLabelMsg")
                    .addBody("sn", printer.getSn())
                    .addBody("content", content)
                    .addBody("sig", SecureUtil.sha1().digestHex(printer.getUser() + printer.getUkey() + stime))
                    .executeAsString();
            log.info("飞鹅打印机响应 res={}", res);
        } catch (Exception e) {
            log.error("飞鹅打印机打印失败", e);
            throw new FeiEPrintException(new FeiEPrintErrorContext(FeiEPrintErrorContext.MainError.PRINT_ERROR,
                    FeiEPrintErrorContext.SubError.SEND_FAIL, name), "飞鹅打印请求发送失败");
        }
    }

    public static void request(String user, String ukey, String sn, String content) {
        try {
            String stime = String.valueOf(System.currentTimeMillis() / 1000);
            String res = Forest.post("https://api.feieyun.cn/Api/Open/")
                    .contentFormUrlEncoded()
                    .addBody("user", user)
                    .addBody("stime", stime)
                    .addBody("apiname", "Open_printLabelMsg")
                    .addBody("sn", sn)
                    .addBody("content", content)
                    .addBody("sig", SecureUtil.sha1().digestHex(user + ukey + stime))
                    .executeAsString();
            log.info("飞鹅打印机响应 res={}", res);
        } catch (Exception e) {
            log.error("飞鹅打印机打印失败", e);
            throw new FeiEPrintException(new FeiEPrintErrorContext(FeiEPrintErrorContext.MainError.PRINT_ERROR,
                    FeiEPrintErrorContext.SubError.SEND_FAIL, ""), "飞鹅打印请求发送失败");
        }
    }
}
